﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MonoTorrent;
using MonoTorrent.Dht;
using MonoTorrent.Dht.Listeners;
using MonoTorrent.Tracker.Listeners;

namespace TorrentsCrawler
{
    class Program
    {
        static List<IPEndPoint> bootstraps;

        static void Main(string[] args)
        {
            //bootstraps = new List<IPEndPoint>()
            //{
            //     new IPEndPoint(IPAddress.Parse("82.221.103.244"),6881),
            //     new IPEndPoint(IPAddress.Parse("67.215.246.10"),6881)
            //};

            DhtListener listener = new DhtListener(new IPEndPoint(IPAddress.Parse("0.0.0.0"), 40050));
            DhtEngine engine = new DhtEngine(listener);
            
            byte[] nodes = null;
            if (File.Exists("mynodes"))
                nodes = File.ReadAllBytes("mynodes");

            listener.Start();
            engine.PeersFound += delegate (object o, PeersFoundEventArgs e)
            {
                Console.WriteLine("I FOUND PEERS: {0}", e.Peers.Count);
                engine.Start(nodes);
                engine.PeersFound += Engine_PeersFound;
                Random random = new Random(5);
                byte[] b = new byte[20];
                lock (random)
                    random.NextBytes(b);

                while (Console.ReadLine() != "q")
                {
                    for (int i = 0; i < 30; i++)
                    {
                        Console.WriteLine("Waiting: {0} seconds left", (30 - i));
                        System.Threading.Thread.Sleep(1000);
                    }
                    // Get some peers for the torrent
                    
                    engine.GetPeers(new InfoHash(b));
                    random.NextBytes(b);
                }
                File.WriteAllBytes("mynodes", engine.SaveNodes());
            };

            while (true)
            {
                Thread.Sleep(1000);
            }
        }

        private static void Engine_PeersFound(object sender, PeersFoundEventArgs e)
        {
            Console.WriteLine("PeersFound:" + e.InfoHash.ToHex());
        }
    }
}
